package main

import (
	"flag"
	"fmt"
	"geecache"
	"log"
	"net/http"
)

type server int

func (s server) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	log.Printf("url is %s\n", request.Host)
	writer.Write([]byte("hello world"))

}

var db = map[string]string{
	"tom":  "630",
	"Jack": "630",
	"Sam":  "630",
}

var nodes = []geecache.HttpPeerGetter{
	geecache.NewHttpPeerGetter("127.0.0.1", 8001),
	geecache.NewHttpPeerGetter("127.0.0.1", 8002),
	geecache.NewHttpPeerGetter("127.0.0.1", 8003),
}

func main() {
	var mainType string
	var port int
	var api bool
	flag.StringVar(&mainType, "t", "cache", "服务类型 cache 是缓存,http是服务")
	flag.IntVar(&port, "port", 9999, "节点访问端口")
	flag.BoolVar(&api, "api", false, "是否启动api服务 true表示启动")
	flag.Parse()
	fmt.Printf("type is %s\n", mainType)
	switch mainType {
	case "http":
		var s server
		http.ListenAndServe("127.0.0.1:9999", &s)
	case "cache":
		geecache.NewGroup("goods", func(name string) ([]byte, error) {
			if v, ok := db[name]; ok {
				return []byte(v), nil
			} else {
				return nil, fmt.Errorf("未查询到%s\n", name)
			}
		})
		p := geecache.NewHttpPool("127.0.0.1:9999")
		http.ListenAndServe("127.0.0.1:9999", p)
		fmt.Println("waiting..")
	}
}
